package yxy.game.pm2.command.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import yxy.apple.logger.Logger;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.order.OrderInfo;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.message.PayMessage;
import yxy.game.pm2.message.PayMessage.DealOrderRequest;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.pay.PostUtil;

import java.util.ArrayList;

@MessageType(proto = Command.DealOrder, classtype = PayMessage.DealOrderRequest.class)
public class CMD_DealOrder extends Command<DealOrderRequest> {

	private static final int success = 1;	//成功
	private static final int noorder = 2;	//订单不存在
	private static final int failed = 3;	//失败
	
	private static final Logger logger = Logger.create(CMD_DealOrder.class);
	
	@Override
	public void execute(MessageSource messageSource, DealOrderRequest request) throws Exception {
		String playercode = messageSource.getTag();		
		PayMessage.DealOrderResponse.Builder response = PayMessage.DealOrderResponse.newBuilder();
		
		String channel = request.getChannel();
		String info = request.getInfo();
		logger.info("CMD_DealOrder info :" + info);
		
		JSONObject postjson = JSON.parseObject(info);
		if(!postjson.containsKey("developerPayload")) {
			send(messageSource, response, Result.DataError);
			return;
		}
		
		String developerPayload = postjson.getString("developerPayload");
		
		try {
			if(OrderInfo.lockOrderInfo(playercode)) {

				OrderInfo oi = OrderInfo.get(playercode, developerPayload);
				
				response.setInfo(info);
				
				if(oi != null) {
					if(oi.getOrderstate() == OrderInfoModule.orderinfofail) {
						send(messageSource, response, Result.DataError);
						return;
					}
					if(oi.getOrderstate() == OrderInfoModule.orderinfofinish) {
						send(messageSource, response, Result.ActHadGet);
						return;
					}
					if(oi.getOrderstate() == OrderInfoModule.orderinforuning) {
						send(messageSource, response, Result.Success);
						return;
					}
				}
				
				switch (channel) {
					case SdkChannel.sdk_huawei:{
						String ret = "";
						String url = "http://ydsgjhg.ios.tjyouai.com:20000/huawei2";
						try {
							NameValuePair[] pair = PostUtil.getValuePair(postjson);
							ret = PostUtil.doPost(url, pair, 30000);
						} catch (Exception e) {
							e.printStackTrace();
						}
						logger.info(getClass().getSimpleName() + " ret:" + ret);

						if (ret == null || ret.equals("")) {
							send(messageSource, response, Result.DataError);
							return;
						}
						JSONObject retjson = JSON.parseObject(ret);
						int result = retjson.getIntValue("result");
						
						if(result == success) {

							oi = OrderInfo.get(playercode, developerPayload);
							dealGoodsReward(playercode, oi);
							addItem(response, oi.getCurs());
							send(messageSource, response, Result.Success);
						}else {
							send(messageSource, response, Result.PayFail);
							return;
						}
						
						break;
					}
					

					default:{
						send(messageSource, response, Result.DataError);
						return;
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			OrderInfo.unlockOrderInfo(playercode);
		}
		
		
		
	
		
	}

	private void send(MessageSource messageSource, PayMessage.DealOrderResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
	
	private void dealGoodsReward(String playercode, OrderInfo oi) {
		int fristgold = 0;
		try {
			fristgold = ActiveModule.getFirstGold(playercode, oi.getGoodsid());
		} catch (Exception e) {
			e.printStackTrace();
		}

		OrderInfoModule.dealFinishOrderInfo(oi);
		ArrayList<Currency> curs = oi.getCurs();
		if (fristgold != 0) {
			Currency cur = Currency.create(CurrencyType.CT_元宝, -1, fristgold);
			curs.add(cur);
			curs = new ArrayList<Currency>(Currency.merge(curs));
		}

		new CurrencyHandle().addCurrency(playercode, CCReason.用户购买, curs);
		ActiveModule.HandleActiveAddVipexp(playercode, oi);
	}
	
	private void addItem(PayMessage.DealOrderResponse.Builder response, ArrayList<Currency> curs){
		for (Currency cur : curs) {
			PackageMessage.Item.Builder item = PackageMessage.Item.newBuilder();

			item.setType(cur.getType().getNumber());
			item.setDataId(cur.getDataId());
			item.setNumber(cur.getNumber());
			response.addCurs(item.build());
		}
	}
}
